import requests
import json
import sys

url = 'http://localhost/v1/chat-messages'
headers = {
    'Authorization': 'Bearer app-wcpS7Lnfdkp1UNQEscTt8oV1',
    'Content-Type': 'application/json',
}
data = {
    "inputs": {},
    "query": "现在几点钟",
    "response_mode": "streaming",
    "conversation_id": "",
    "user": "abc-123",
}

# # 方法1: 使用 stream=True 参数处理流式响应
# print("=== 方法1: 逐块处理流式数据 ===")
# response = requests.post(url, headers=headers, data=json.dumps(data), stream=True)

# # 检查响应状态
# if response.status_code == 200:
#     print("开始接收流式数据...")
#     for chunk in response.iter_content(chunk_size=1024, decode_unicode=True):
#         if chunk:
#             # 打印每个数据块
#             print(f"{chunk}", end='')
#             sys.stdout.flush()  # 强制刷新输出缓冲区
# else:
#     print(f"请求失败，状态码: {response.status_code}")
#     print(f"错误信息: {response.text}")

# print("\n\n=== 方法2: 逐行处理流式数据 ===")
# # 重新发送请求
# response2 = requests.post(url, headers=headers, data=json.dumps(data), stream=True)

# if response2.status_code == 200:
#     print("开始逐行接收流式数据...")
#     for line in response2.iter_lines(decode_unicode=True):
#         if line:
#             print(f"接收到行: {line}")
#             # 如果是 JSON 格式，可以尝试解析
#             if line.startswith('data: '):
#                 try:
#                     json_data = json.loads(line[6:])  # 去掉 'data: ' 前缀
#                     print(f"解析的JSON: {json_data}")
#                 except json.JSONDecodeError:
#                     print(f"无法解析的数据: {line}")
# else:
#     print(f"请求失败，状态码: {response2.status_code}")
#     print(f"错误信息: {response2.text}")




# 重新发送请求
response3 = requests.post(url, headers=headers, data=json.dumps(data), stream=True)

if response3.status_code == 200:
    print("开始接收流式数据...\n")
    for line in response3.iter_lines(decode_unicode=True):
        if line:
            line = line.strip()
            data_content = ""
            if line.startswith('data: '):
                data_content = line[6:]
            elif line.startswith('event: '):
                data_content = line[7:]
            try:
                json_data = json.loads(data_content)
                # 根据实际数据结构提取内容
                if 'event' in json_data and json_data['event'] == 'message_end':
                    print("\n消息结束\n")

                if 'answer' in json_data:   
                    print(json_data['answer'], end='')
                    with open('result.txt', 'a', encoding='utf-8') as f:
                        f.write(json_data['answer'])
                sys.stdout.flush()
            except json.JSONDecodeError:
                pass
                # print(f"非JSON数据: {data_content}")

else:
    print(f"请求失败，状态码: {response3.status_code}")
    print(f"错误信息: {response3.text}")
